package com.example.demo_yunpan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo_yunpan.domain.LoginUser;
import com.example.demo_yunpan.mapper.UserMapper;
import com.example.demo_yunpan.entity.user;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{

        //查询用户信息
        LambdaQueryWrapper<user> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user::getUserName,username);
        user user = userMapper.selectOne(queryWrapper);
        System.out.println(user.getUserName());
        System.out.println(user.getUserPass());
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误：用户不存在");
        }
        //查询权限信息
        //由于我们自定义了3个权限，所以用List集合存储。注意权限实际就是'有特殊含义的字符串'，所以下面的三个字符串就是自定义的
        //下面那行就是我们的权限集合，等下还要在LoginUser类做权限集合的转换
        //List<String> list = new ArrayList<>(Arrays.asList("test","adminAuth","huanfAuth"));
        //-------------------------------查询来自数据库的权限信息--------------------------------
        List<String> list = userMapper.selectUserNameByUserId(String.valueOf(user.getUserId()));

        //------------------------------------------------------------------------------

        //把查询到的user结果，封装成UserDetails类型，然后返回。
        //但是由于UserDetails是个接口，所以我们先需要在domino目录新建LoginUser类，作为UserDetails的实现类，再写下面那行
        return new LoginUser(user,list); //这里传了第二个参数，表示的是权限信息
    }
}
